﻿using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;

using Core.Localization;
using Core.Model;

namespace Core.Logic
{
    public class ModelManager
    {
		public ModelManager(LocalizationManager localizationManager)
		{
			_localizationManager = localizationManager;
		}

		#region Private fields

		private CompositionContainer _container;

	    private readonly LocalizationManager _localizationManager;

		#endregion

		#region Public fields

		[ImportMany]
	    public IEnumerable<IExaminationModel> Models { get; private set; }

		#endregion

		#region Public methods

	    public void Load(string modelsPath)
	    {
		    var catalog = new AggregateCatalog();
		    try
		    {
			    catalog.Catalogs.Add(new DirectoryCatalog(modelsPath));
		    }
		    catch (DirectoryNotFoundException)
		    {
				Models = new List<IExaminationModel>();
				return;
		    }

		    _container = new CompositionContainer(catalog);
			_container.ComposeExportedValue(_localizationManager);
		    try
		    {
			    _container.ComposeParts(this);
		    }
		    catch (CompositionException)
		    {
			    throw new FileLoadException();
		    }
	    }

	    #endregion
	}
}